<?php

namespace Biz\service\SamsungActivity;


use Biz\cache\samsungActivity\SamsungActivityCache;
use Biz\model\SamsungActivity\SamsungJoinUserListModel;
use Doraemon\model\Comment;
use Doraemon\model\CommentMasterStat;
use Doraemon\model\Member as mMember;
use Doraemon\service\User;
use Doraemon\tools\Ip;

class SamsungJoinUserListService
{

    const SAVE_TYPE_OUTPUT = 1; //save('php://output')
    const SAVE_TYPE_FILE = 2;//save($filePath)

    /**
     * @param $list
     * @param int $saveType
     * @param string $pageTitle
     * @return \PhpOffice\PhpSpreadsheet\Writer\IWriter
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     */
    public static function exportList(
        $list,
        int $saveType = self::SAVE_TYPE_FILE,
        string $pageTitle
    ): \PhpOffice\PhpSpreadsheet\Writer\IWriter {
        $uidArr = array_unique(array_filter(array_column($list, 'uid')));
        $data = [];
        $userList = User::getBatchBasicUserInfo($uidArr);
        $userList = array_column($userList, null, 'uid');
        foreach ($list as $row) {
            $userInfo = [];
            $uid = $row['uid'];
            if ($uid > 0) {
                $userInfo = (isset($userList[$uid])) ? $userList[$uid] : [];
            }
            $dataRow = [
                'id' => $row['id'],
                'uid' => $uid ?? '',
                'nick' => $userInfo ? $userInfo['nick'] : $row['nick'],
                'name' => $row['name'] ?? '',
                'phone' => $row['phone'] ?? '',
                'profession_name' => $userInfo ? mMember::$typeDesc[$userInfo['type']] : $row['profession_name'],
                'agency' => $row['agency'] ?? '',
                'idea' => $row['idea'] ?? '',
                'desc' => $row['desc'] ?? '',
                'tv_type_name' => $row['tv_type_name'] ?? '',
                'artist_name' => $row['artist_name'] ?? '',
            ];
            $designImgPath = sys_get_temp_dir().DIRECTORY_SEPARATOR.'SamsungActivity'.DIRECTORY_SEPARATOR;
            if (!file_exists($designImgPath)) {
                mkdir($designImgPath);
            }
            if (!empty($row['imgs_url'])) {
                for ($i = 1; $i <= 5; $i++) {
                    $designImgFile = '';
                    if (isset($row['imgs_url'][$i - 1]) && !empty($row['imgs_url'][$i - 1])) {
                        $imgUrl = $row['imgs_url'][$i - 1];
                        $designImgFile = $designImgPath.$row['id'].'_'.$i;
                        if (!file_exists($designImgFile)) {
                            SamsungJoinUserListService::download($imgUrl, $designImgFile);
                        }
                    }
                    $dataRow['design_img_url_'.$i] = $designImgFile;

                }
            }
            $imgUrlOriDownload = '';
            if (isset($row['imgs_ori_url']) && !empty($row['imgs_ori_url'])) {
                foreach ($row['imgs_ori_url'] as $imgUrlOri) {
                    $imgUrlOriDownload .= $imgUrlOri.PHP_EOL.PHP_EOL;
                }
            }
            $dataRow['imgs_url_ori_download'] = $imgUrlOriDownload;
            $dataRow['addtime'] = $row['addtime'];
            $data[$row['id']] = $dataRow;
        }
        $title = [
            'id',
            'uid',
            '昵称',
            '姓名',
            '手机号',
            '职业',
            '机构',
            '设计理念',
            '描述',
            '电视型号',
            '所选艺术家',
            '设计图第一张',
            '设计图第二张',
            '设计图第三张',
            '设计图第四张',
            '设计图第五张',
            '原图下载',
            '提交时间',
        ];
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $titCol = 'A';
        foreach ($title as $value) {
            // 单元格内容写入
            $sheet->setCellValue($titCol.'1', $value);
            $styleArray = [
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                    'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                ],
            ];
            $sheet->getStyle($titCol.'1')->applyFromArray($styleArray);
            $titCol++;
        }
        $sheet->getColumnDimension('A')->setWidth(15);//id
        $sheet->getColumnDimension('B')->setWidth(15);//uid
        $sheet->getColumnDimension('C')->setWidth(15);//昵称
        $sheet->getColumnDimension('D')->setWidth(15);//姓名
        $sheet->getColumnDimension('E')->setWidth(15);//手机号
        $sheet->getColumnDimension('F')->setWidth(15);//职业
        $sheet->getColumnDimension('G')->setWidth(15);//机构
        $sheet->getColumnDimension('H')->setWidth(100);//设计理念
        $sheet->getColumnDimension('I')->setWidth(100);//描述
        $sheet->getColumnDimension('J')->setWidth(15);//电视型号
        $sheet->getColumnDimension('K')->setWidth(15);//所选艺术家
        $sheet->getColumnDimension('L')->setWidth(50);//设计图第一张
        $sheet->getColumnDimension('M')->setWidth(50);//设计图第二张
        $sheet->getColumnDimension('N')->setWidth(50);//设计图第三张
        $sheet->getColumnDimension('O')->setWidth(50);//设计图第四张
        $sheet->getColumnDimension('P')->setWidth(50);//设计图第五张
        $sheet->getColumnDimension('Q')->setWidth(70);//原图下载
        $sheet->getColumnDimension('R')->setWidth(20);//提交时间
        $row = 2; // 从第二行开始
        foreach ($data as $id => $item) {
            $dataCol = 'A';
            foreach ($item as $key => $value) {
                $cellKey = $dataCol.$row;
                if (in_array($key, [
                        'design_img_url_1',
                        'design_img_url_2',
                        'design_img_url_3',
                        'design_img_url_4',
                        'design_img_url_5',
                    ]) && !empty($value)) {
                    $drawing[$cellKey] = new \PhpOffice\PhpSpreadsheet\Worksheet\Drawing();
                    $drawing[$cellKey]->setName('图片');
                    $drawing[$cellKey]->setDescription('图片');
                    $drawing[$cellKey]->setPath($value);
                    $drawing[$cellKey]->setWidth(200);
                    $drawing[$cellKey]->setHeight(200);
                    $drawing[$cellKey]->setCoordinates($cellKey);
                    $drawing[$cellKey]->setOffsetX(10);
                    $drawing[$cellKey]->setOffsetY(10);
                    $drawing[$cellKey]->setWorksheet($sheet);
                } else {
                    $sheet->setCellValue($cellKey, $value);
                    $sheet->getStyle($cellKey)->getAlignment()->setWrapText(true);
                }
                $sheet->getRowDimension($row)->setRowHeight(200);
                $styleArray = [
                    'alignment' => [
                        'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                        'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER,
                    ],
                ];
                $sheet->getStyle($cellKey)->applyFromArray($styleArray);
                $dataCol++;
            }
            $row++;
        }
        $fileName = $pageTitle.'.xlsx';
        ob_end_clean();
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'.$fileName.'"');
        header('Cache-Control: max-age=0');
        header('Cache-Control: max-age=1');
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        if (self::SAVE_TYPE_OUTPUT == $saveType) {
            $writer->save('php://output');

        } else {
            $filePath = sys_get_temp_dir().DIRECTORY_SEPARATOR.$fileName;
            $writer->save($filePath);
        }

        return $writer;
    }

    public static function download($url, $filename)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        $file = curl_exec($ch);
        curl_close($ch);
        $resource = fopen($filename, 'a');
        fwrite($resource, $file);
        fclose($resource);

        return $filename;
    }

    /**
     * 作品广场顶部接口（弹幕数据）
     * @return array
     */
    public static function getComment(): array
    {
        $data = [];
        $objId = SamsungJoinUserListModel::getRelationObjId();
        $commentsStatList = CommentMasterStat::select(['origin_id', 'like_num'], [
            'obj_id' => $objId,
            'like_num[>]' => 0,
            'status' => CommentMasterStat::STATUS_NORMAL,
            'ORDER' => ['like_num' => 'DESC'],
        ]);
        $commentsOriginIds = array_column($commentsStatList, 'origin_id');
        if ($commentsOriginIds) {
            $commentList = Comment::select('*',
                ['id' => $commentsOriginIds, 'obj_id' => $objId, 'status' => Comment::STATUS_NORMAL]);
            $commentList = array_column($commentList, null, 'id');
            if (!empty($commentList)) {
                foreach ($commentsOriginIds as $id) {
                    if (isset($commentList[$id]) && $commentList[$id]['content'] && $commentList[$id]['uid'] > 0) {
                        $data[] = [
                            'id' => $id,
                            'obj_id' => $objId,
                            'content' => $commentList[$id]['content'] ?? '',
                            'uid' => $commentList[$id]['uid'] ?? 0,
                        ];
                    }
                }
            }
        }

        return $data;

    }

    /**
     * 作品列表数据
     * @param $uid
     * @param $artistId
     * @return array
     */
    public static function getList($uid, $artistId): array
    {
        $where = [
            'status' => SamsungJoinUserListModel::STATUS_SHOW,
            'artist_id' => $artistId,
            'ORDER' => ['vote_init' => 'ASC'],
        ];
        $list = SamsungJoinUserListModel::selectByWhere($where,
            ['id', 'uid', 'name', 'nick', 'avatar', 'cover_img', 'artist_id', 'idea']);
        $data = [];
        if ($list) {
            //获取用户信息
            $uidArr = array_unique(array_filter(array_column($list, 'uid')));
            $userList = User::getBasicUserInfosByCache($uidArr);
            $userList = array_column($userList, null, 'uid');

            //获取当前用户当日已投票数据
            $userVote = SamsungActivityCache::getTodayUserVote($uid);

            //获取top1
            $top1Id = self::getTop1Id();
            foreach ($list as $row) {
                $uid = $row['uid'];
                $nick = '';
                $avatar = '';
                if ($uid > 0) {
                    $userInfo = (isset($userList[$uid])) ? $userList[$uid] : [];
                    if (!empty($userInfo)) {
                        $nick = $userInfo['nick'];
                        $avatar = $userInfo['avatar_small'];
                    }
                } else {
                    $nick = $row['nick'] ?: $row['name'];
                    $avatar = $row['avatar_url'] ?? '';
                }
                $dataRow = [
                    'id' => $row['id'],
                    'uid' => $uid ?? 0,
                    'nick' => $nick,
                    'avatar' => $avatar,
                    'idea' => $row['idea'] ?? '',
                    'cover_img' => $row['cover_img_url'] ?? '',
                    'artist_name' => $row['artist_name'] ?? '',
                    'is_vote' => (int)in_array($row['id'], $userVote),//1：已投票；0：未投票，可继续投票
                    'is_top1' => (int)($top1Id == $row['id']),// 1：是top1 ，0：不是top1
                    'is_show_vote' => SamsungJoinUserListModel::isCanVote(),//是否展示投票按钮 1:展示，0:不展示
                ];
                $data[] = $dataRow;
            }
        }

        return $data;

    }

    /**
     * 获取投票数为top1的作品id
     * @return array|mixed
     */
    public static function getTop1Id()
    {
        $where = [
            'status' => SamsungJoinUserListModel::STATUS_SHOW,
            'ORDER' => ['vote' => 'DESC'],
            'LIMIT' => 1,
        ];

        return SamsungJoinUserListModel::getByWhere($where, 'id');
    }

    public static function getSecretId(): string
    {
        //根据ua以及ip生成uid
        $ua = $_SERVER['HTTP_USER_AGENT'];
        $ip = Ip::getClientIp();

        return md5($ua.SamsungJoinUserListModel::SECRET_SALT.$ip);
    }

    /**
     * 获取可投票的作品id
     * @return array
     */
    public static function getShowArtworkData(): array
    {
        $where = [
            'status' => SamsungJoinUserListModel::STATUS_SHOW,
        ];

        return SamsungJoinUserListModel::selectByWhere($where);
    }
}